package com.yololabelmaker;

import javax.swing.*;
import java.awt.datatransfer.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.List;

public class ImageTransferHandler extends TransferHandler {
    private CImgArea imgArea;
    
    public ImageTransferHandler(CImgArea imgArea) {
        this.imgArea = imgArea;
    }
    
    @Override
    public boolean canImport(TransferSupport support) {
        // 检查是否支持文件列表或文本（URL）
        if (support.isDataFlavorSupported(DataFlavor.javaFileListFlavor) || 
            support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            return true;
        }
        return false;
    }
    
    @Override
    public boolean importData(TransferSupport support) {
        if (!canImport(support)) {
            return false;
        }
        
        // 尝试获取文件列表
        if (support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            try {
                @SuppressWarnings("unchecked")
                List<File> files = (List<File>) support.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
                
                for (File file : files) {
                    if (isImageFile(file)) {
                        BufferedImage image = javax.imageio.ImageIO.read(file);
                        if (image != null) {
                            imgArea.setImage(image, file.getAbsolutePath());
                            return true;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        // 尝试获取文本（可能是URL）
        if (support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            try {
                String text = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor);
                if (isValidUrl(text)) {
                    URL url = new URL(text);
                    BufferedImage image = javax.imageio.ImageIO.read(url);
                    if (image != null) {
                        // 对于网络图片，创建一个临时文件路径作为标识
                        String tempPath = "network_image_" + System.currentTimeMillis() + "." + getFileExtensionFromUrl(text);
                        imgArea.setImage(image, tempPath);
                        return true;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        return false;
    }
    
    // 检查文件是否是图片文件
    private boolean isImageFile(File file) {
        if (!file.isFile()) {
            return false;
        }
        String fileName = file.getName().toLowerCase();
        return fileName.endsWith(".jpg") || 
               fileName.endsWith(".jpeg") || 
               fileName.endsWith(".png") || 
               fileName.endsWith(".gif");
    }
    
    // 检查文本是否是有效的URL
    private boolean isValidUrl(String text) {
        return text.toLowerCase().startsWith("http://") || 
               text.toLowerCase().startsWith("https://") ||
               text.toLowerCase().startsWith("smb://");
    }
    
    // 从URL获取文件扩展名
    private String getFileExtensionFromUrl(String urlString) {
        String extension = "jpg";
        int lastDotIndex = urlString.lastIndexOf('.');
        if (lastDotIndex > 0) {
            String potentialExtension = urlString.substring(lastDotIndex + 1).toLowerCase();
            // 检查是否是有效的图片扩展名
            if (potentialExtension.matches("^(jpg|jpeg|png|gif)$")) {
                extension = potentialExtension;
            }
        }
        return extension;
    }
}